<template>
    <div class="editable-section" v-if="aiContent">
        <div class="card">
            <div class="card-header">
                <h2>一、核心问题梳理</h2>
                <el-button class="locate-btn" @click="scrollToSection('核心问题梳理')" text>
                    <el-icon>
                        <Location />
                    </el-icon>
                </el-button>
            </div>
            <draggable class="editable-list" v-model="problemList" item-key="id" handle=".drag-handle"
                @start="drag = true" @end="drag = false">
                <template #item="{ element }">
                    <div class="editable-item">
                        <div class="item-content">
                            <div class="drag-handle">
                                <el-icon>
                                    <Rank />
                                </el-icon>
                            </div>
                            <div class="content-header">
                                <div class="input-group">
                                    <div class="input-label">问题：</div>
                                    <el-input v-model="problemInputs[element.id]"
                                        @change="updateProblemAnalysis(element.id)" 
                                        type="textarea" 
                                        autosize
                                        placeholder="输入问题" />
                                </div>
                                <div class="input-group">
                                    <div class="input-label">分析：</div>
                                    <el-input v-model="analysisInputs[element.id]"
                                        @change="updateProblemAnalysis(element.id)" 
                                        type="textarea" 
                                        autosize
                                        placeholder="输入分析" />
                                </div>
                            </div>

                            <el-button class="delete-btn" @click="removeItem('一、核心问题梳理', element.id)" text>
                                删除
                            </el-button>
                        </div>
                    </div>
                </template>
            </draggable>
            <el-button type="primary" @click="addItem('一、核心问题梳理')">添加项目</el-button>
        </div>

        <div class="card">
            <div class="card-header">
                <h2>二、运营方向建议</h2>
                <el-button class="locate-btn" @click="scrollToSection('运营方向建议')" text>
                    <el-icon>
                        <Location />
                    </el-icon>
                </el-button>
            </div>
            <div class="editable-table">
                <table>
                    <draggable v-model="tableItems['二、运营方向建议']" item-key="id" handle=".drag-handle" tag="tbody"
                        @start="drag = true" @end="drag = false">
                        <template #item="{ element }">
                            <tr align="center" valign="middle">
                                <td valign="middle" class="drag-handle" style="width: 40px">
                                    <el-icon>
                                        <Rank />
                                    </el-icon>
                                </td>
                                <td>
                                    <el-input v-model="element.模块" type="textarea" autosize />
                                </td>
                                <td>
                                    <el-input v-model="element.优化方向" type="textarea" autosize />
                                </td>
                                <td style="width: 80px">
                                    <el-button class="delete-btn" @click="removeTableRow('二、运营方向建议', element.id)" text>
                                        删除
                                    </el-button>
                                </td>
                            </tr>
                        </template>
                    </draggable>
                </table>
            </div>
            <el-button type="primary" @click="addTableRow('二、运营方向建议')">添加行</el-button>
        </div>

        <div class="card">
            <div class="card-header">
                <h2>三、行动建议</h2>
                <el-button class="locate-btn" @click="scrollToSection('行动建议')" text>
                    <el-icon>
                        <Location />
                    </el-icon>
                </el-button>
            </div>
            <div class="editable-table">
                <table>
                    <draggable v-model="tableItems['三、行动建议']" item-key="id" handle=".drag-handle" tag="tbody"
                        @start="drag = true" @end="drag = false">
                        <template #item="{ element }">
                            <tr>
                                <td class="drag-handle" style="width: 40px">
                                    <el-icon>
                                        <Rank />
                                    </el-icon>
                                </td>
                                <td>
                                    <el-input v-model="element.问题点" type="textarea" autosize />
                                </td>
                                <td>
                                    <div style="width: 95%;">
                                        <el-input v-for="(action, idx) in element.推荐动作" :key="idx"
                                            :data-action-id="element.id"
                                            @keydown.enter.prevent="handleActionEnter(element, idx)"
                                            @keydown.backspace="(e) => handleActionBackspace(e, element, idx)"
                                            v-model="element.推荐动作[idx]" type="text" :rows="1"
                                            :style="{ marginTop: idx > 0 ? '8px' : '0px' }" />
                                    </div>
                                </td>
                                <td style="width: 80px">
                                    <el-button class="delete-btn" @click="removeTableRow('三、行动建议', element.id)" text>
                                        删除
                                    </el-button>
                                </td>
                            </tr>
                        </template>
                    </draggable>
                </table>
            </div>
            <el-button type="primary" @click="addTableRow('三、行动建议')">添加行</el-button>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, watch, computed, nextTick } from 'vue'
import { Location, Rank } from '@element-plus/icons-vue'
import type { AnalysisResult } from '../api'
import draggable from 'vuedraggable'

const props = defineProps<{
    aiContent: AnalysisResult | null
}>()

// 用于存储拆分后的问题和分析输入
const problemInputs = ref<string[]>([])
const analysisInputs = ref<string[]>([])

// 监听 aiContent 变化,初始化输入数据
watch(() => props.aiContent?.['一、核心问题梳理'], (newVal) => {
    if (!newVal) return

    problemInputs.value = []
    analysisInputs.value = []

    newVal.forEach((item: string) => {
        const match = item.match(/【(.+?)】，(.+)/)
        if (match) {
            problemInputs.value.push(match[1])
            analysisInputs.value.push(match[2])
        } else {
            problemInputs.value.push('')
            analysisInputs.value.push('')
        }
    })
}, { immediate: true })

// 修改添加表格行的方法，确保初始状态有两个输入框
const addTableRow = (section: '二、运营方向建议' | '三、行动建议') => {
    if (!props.aiContent) return

    if (section === '二、运营方向建议') {
        props.aiContent[section]['模块'].push('')
        props.aiContent[section]['优化方向'].push('')
        tableItems.value[section].push({
            id: tableItems.value[section].length,
            模块: '',
            优化方向: ''
        })
    } else if (section === '三、行动建议') {
        props.aiContent[section]['问题点'].push('')
        props.aiContent[section]['推荐动作'].push([''])  // 修改为只有一个空字符串
        tableItems.value[section].push({
            id: tableItems.value[section].length,
            问题点: '',
            推荐动作: ['']  // 修改为只有一个空字符串
        })
    }
}

// 修改处理推荐动作输入框回车事件的方法
const handleActionEnter = (element: TableItem三, currentIndex: number) => {
    const currentValue = element.推荐动作[currentIndex].trim()
    
    // 如果当前输入框为空，不做任何处理
    if (!currentValue) return
    
    // 检查是否已经有空输入框
    const emptyInputIndex = element.推荐动作.findIndex((action, idx) => 
        idx !== currentIndex && !action.trim()
    )
    
    if (emptyInputIndex === -1) {
        // 没有空输入框，添加新的
        element.推荐动作.push('')
        nextTick(() => {
            const inputs = document.querySelectorAll(`[data-action-id="${element.id}"]`) as NodeListOf<HTMLInputElement>
            const lastInput = inputs[inputs.length - 1]
            if (lastInput) lastInput.focus()
        })
    } else {
        // 已有空输入框，直接聚焦
        nextTick(() => {
            const inputs = document.querySelectorAll(`[data-action-id="${element.id}"]`) as NodeListOf<HTMLInputElement>
            const emptyInput = inputs[emptyInputIndex]
            if (emptyInput) emptyInput.focus()
        })
    }
}

// 修改处理推荐动作输入框backspace事件的方法
const handleActionBackspace = (e: KeyboardEvent, element: TableItem三, currentIndex: number) => {
    const input = e.target as HTMLInputElement
    
    // 只在输入框为空且不是第一个输入框时处理
    if (input.value === '' && currentIndex > 0) {
        e.preventDefault() // 阻止默认的退格行为
        
        // 删除当前空输入框
        element.推荐动作.splice(currentIndex, 1)
        
        // 聚焦到上一个输入框
        nextTick(() => {
            const inputs = document.querySelectorAll(`[data-action-id="${element.id}"]`) as NodeListOf<HTMLInputElement>
            const prevInput = inputs[currentIndex - 1]
            if (prevInput) {
                prevInput.focus()
                // 将光标移到文本末尾
                const length = prevInput.value.length
                prevInput.setSelectionRange(length, length)
            }
        })
    }
}

// 创建一个计算属性来处理问题列表
const problemList = computed({
    get: () => {
        if (!props.aiContent) return []
        return props.aiContent['一、核心问题梳理'].map((_, index) => ({
            id: index,
            problem: problemInputs.value[index],
            analysis: analysisInputs.value[index]
        }))
    },
    set: (newValue) => {
        if (!props.aiContent) return
        // 重新排序 problemInputs 和 analysisInputs
        const newProblemInputs: string[] = []
        const newAnalysisInputs: string[] = []
        newValue.forEach(item => {
            newProblemInputs.push(problemInputs.value[item.id])
            newAnalysisInputs.push(analysisInputs.value[item.id])
        })
        problemInputs.value = newProblemInputs
        analysisInputs.value = newAnalysisInputs
        // 更新原始数据
        props.aiContent['一、核心问题梳理'] = newValue.map((_, index) =>
            `【${newProblemInputs[index]}】，${newAnalysisInputs[index]}`
        )
    }
})

// 更新问题分析组合
const updateProblemAnalysis = (index: number) => {
    if (!props.aiContent) return

    const problem = problemInputs.value[index]
    const analysis = analysisInputs.value[index]
    props.aiContent['一、核心问题梳理'][index] = `【${problem}】，${analysis}`
}

// 添加项目方法
const addItem = (section: keyof AnalysisResult) => {
    if (props.aiContent) {
        (props.aiContent[section] as string[]).push('【】，')
        problemInputs.value.push('')
        analysisInputs.value.push('')
    }
}

// 删除项目方法
const removeItem = (section: keyof AnalysisResult, index: number) => {
    if (props.aiContent) {
        (props.aiContent[section] as string[]).splice(index, 1)
        problemInputs.value.splice(index, 1)
        analysisInputs.value.splice(index, 1)
    }
}

// 删除表格行
const removeTableRow = (section: '二、运营方向建议' | '三、行动建议', index: number) => {
    if (!props.aiContent) return

    if (section === '二、运营方向建议') {
        props.aiContent[section]['模块'].splice(index, 1)
        props.aiContent[section]['优化方向'].splice(index, 1)
        tableItems.value[section].splice(index, 1)
    } else if (section === '三、行动建议') {
        props.aiContent[section]['问题点'].splice(index, 1)
        props.aiContent[section]['推荐动作'].splice(index, 1)
        tableItems.value[section].splice(index, 1)
    }
}

// 滚动到对应区域
const scrollToSection = (section: string) => {
    const container = document.getElementById('report-container')
    const targetElement = container?.querySelector(`[data-section="${section}"]`)

    if (targetElement && container) {
        // 获取容器的滚动位置和视口高度
        const containerRect = container.getBoundingClientRect()
        const targetRect = targetElement.getBoundingClientRect()

        // 计算目标位置：目标元素距离顶部的距离 - 容器距离顶部的距离 - 一些偏移量
        const scrollTop = targetRect.top - containerRect.top + container.scrollTop - 80

        container.scrollTo({
            top: scrollTop,
            behavior: 'smooth'
        })
    }
}

const drag = ref(false)

// 首先修改接口定义
interface TableItem二 {
    id: number
    模块: string
    优化方向: string
}

interface TableItem三 {
    id: number
    问题点: string
    推荐动作: string[]
}

interface TableData {
    '二、运营方向建议': TableItem二[]
    '三、行动建议': TableItem三[]
}

// 创建表格数据的响应式引用
const tableItems = ref<TableData>({
    '二、运营方向建议': [],
    '三、行动建议': []
})

// 监听 aiContent 变化，初始化表格数据
watch(() => props.aiContent, (newContent) => {
    if (!newContent) return

    tableItems.value = {
        '二、运营方向建议': newContent['二、运营方向建议']?.['模块']?.map((模块, index) => ({
            id: index,
            模块: 模块 || '',
            优化方向: newContent['二、运营方向建议']?.['优化方向']?.[index] || ''
        })) || [],
        '三、行动建议': newContent['三、行动建议']?.['问题点']?.map((问题点, index) => ({
            id: index,
            问题点: 问题点 || '',
            推荐动作: newContent['三、行动建议']?.['推荐动作']?.[index] || ['']
        })) || []
    }
}, { immediate: true })

// 监听表格数据变化，同步回 aiContent
watch(tableItems, (newValue) => {
    if (!props.aiContent) return

    // 同步"二、运营方向建议"
    const 运营方向 = newValue['二、运营方向建议']
    props.aiContent['二、运营方向建议'] = {
        模块: 运营方向.map(item => item.模块),
        优化方向: 运营方向.map(item => item.优化方向)
    }

    // 同步"三、行动建议"
    const 行动建议 = newValue['三、行动建议']
    props.aiContent['三、行动建议'] = {
        问题点: 行动建议.map(item => item.问题点),
        推荐动作: 行动建议.map(item => item.推荐动作)
    }
}, { deep: true })

</script>

<style scoped>
.editable-section {
    padding: 15px;
    width: 100%;
}

.card {
    margin: 12px 0;
    background: #ffffff;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    padding: 16px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
    width: 100%;
    box-sizing: border-box;
}

.card h2 {
    font-size: 15px;
    font-weight: 600;
    color: #1a365d;
    margin-bottom: 12px;
    padding-bottom: 8px;
    border-bottom: 1px solid #e2e8f0;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
    padding-bottom: 8px;
    border-bottom: 1px solid #e2e8f0;
}

.card-header h2 {
    margin: 0;
    padding: 0;
    border: none;
}

.locate-btn {
    color: #94a3b8;
    padding: 4px;
    font-size: 16px;
    transition: all 0.2s ease;
}

.locate-btn:hover {
    color: #3b82f6;
    transform: translateY(-1px);
}

.editable-list {
    margin-top: 8px;
}

.editable-item {
    display: flex;
    background: #f8fafc;
    border-radius: 6px;
    padding: 12px;
    margin-bottom: 8px;
}

.item-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex: 1;
    gap: 8px;
}

.content-header {
    display: flex;
    flex-direction: column;
    width: 100%;
    gap: 8px;
}

.input-group {
    flex: 1;
    display: flex;
    align-items: flex-start;
    gap: 8px;
    min-height: 32px;
    margin-right: 8px;
    position: relative;
    padding-left: 45px;
    /* 与标签宽度相同 */
}

.input-label {
    color: #1a365d;
    font-size: 13px;
    font-weight: 500;
    white-space: nowrap;
    line-height: 32px;
    width: 45px;
    text-align: right;
    padding-right: 8px;
    position: absolute;
    left: 0;
}

.delete-btn {
    color: #94a3b8;
    font-size: 12px;
    padding: 2px 6px;
    height: 32px;
    display: flex;
    align-items: center;
    transition: all 0.2s ease;
}

.delete-btn:hover {
    color: #ef4444;
    background: rgba(239, 68, 68, 0.05);
}

.editable-table {
    margin-top: 10px;
    width: 100%;
}

.editable-table table {
    margin-top: 10px;
    width: 100%;
}

/* 修改表格行样式 */
.editable-table tr {
    display: flex;
    margin-bottom: 8px;
    background: #f8fafc;
    border-radius: 6px;
    padding: 8px;
    width: 100%;
    box-sizing: border-box;
}

/* 修改单元格基础样式 */
.editable-table td {
    display: flex;
    align-items: center;
    /* 改为 block */
    height: auto;
    line-height: 1;
    /* 移除固定宽度 */
    box-sizing: border-box;
}

/* 修改中间两列的样式 */
.editable-table td:nth-child(2),
.editable-table td:nth-child(3) {
    flex: 1 1 auto;
    /* 使用 flex-grow, flex-shrink, flex-basis */
    margin: 0 8px;
    min-width: 0;
}

/* 修改第一列和最后一列的样式 */
.editable-table td:nth-child(1) {
    width: 40px;
    flex: 0 0 40px;
    /* 使用 flex-grow, flex-shrink, flex-basis */
}

.editable-table td:nth-child(4) {
    width: 60px;
    flex: 0 0 60px;
    /* 使用 flex-grow, flex-shrink, flex-basis */
}

/* 确保输入框填满单元格 */
.editable-table td :deep(.el-input),
.editable-table td :deep(.el-textarea) {
    display: block;
    width: 100%;
}

/* 修改输入框容器样式 */
.editable-table td :deep(.el-input__wrapper),
.editable-table td :deep(.el-textarea__wrapper) {
    width: 100%;
    display: block;
    min-height: 32px;
    /* 添加最小高度 */
}

/* 确保文本域可以自由调整大小 */
.editable-table td :deep(.el-textarea__inner) {
    width: 100%;
    resize: vertical;
    /* 允许垂直方向调整大小 */
    min-height: 32px;
    /* 设置最小高度 */
    box-sizing: border-box;
}

:deep(.el-table) {
    --el-table-header-bg-color: #f8fafc;
    --el-table-border-color: #e2e8f0;
    --el-table-header-text-color: #1a365d;
}

:deep(.el-table th.el-table__cell) {
    padding: 8px;
    font-size: 13px;
}

:deep(.el-table td.el-table__cell) {
    padding: 6px 8px;
}

:deep(.el-button) {
    padding: 6px 12px;
    height: 30px;
    font-size: 13px;
}

:deep(.el-button--primary) {
    --el-button-bg-color: #3b82f6;
    --el-button-border-color: #3b82f6;
    --el-button-hover-bg-color: #2563eb;
    --el-button-hover-border-color: #2563eb;
}

:deep(.el-button--danger) {
    --el-button-bg-color: #ef4444;
    --el-button-border-color: #ef4444;
    --el-button-hover-bg-color: #dc2626;
    --el-button-hover-border-color: #dc2626;
}

:deep(.el-table__cell .delete-btn) {
    padding: 4px 8px;
    height: auto;
}

:deep(.el-icon) {
    font-size: 16px;
}

.drag-handle {
    cursor: move;
    color: #94a3b8;
    padding: 4px;
    line-height: 32px;
    height: 32px;
    display: flex;
    align-items: center;
}

.drag-handle:hover {
    color: #3b82f6;
}

/* 拖拽时的样式 */
.sortable-ghost {
    opacity: 0.5;
    background: #f1f5f9;
}

.flip-list-move {
    transition: transform 0.3s;
}

.no-move {
    transition: transform 0s;
}

.ghost {
    opacity: 0.5;
    background: #c8ebfb;
}

.list-group {
    min-height: 20px;
}

.list-group-item {
    cursor: move;
}

.list-group-item i {
    cursor: pointer;
}
</style>